<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import/index?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="addfn">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" type="index" :index="indexTotal" width="66" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{ row }">
              <img v-Imgeser="defaulrImg" :src="row.staffPhoto || defaulrImg" alt="" class="avatar">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatt" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{row}">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="updataPremiss(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delfn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <!-- <el-pagination layout="prev, pager, next" /> -->
          <el-pagination
            :current-page="page"
            :page-sizes="[5, 10, 15]"
            :page-size="size"
            layout="total, sizes, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <AddEmployee :show-dialog.sync="showDialog" />
    <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import AssignRole from './components/assign-role.vue'
import defaulrImg from '@/assets/common/bigUserHeader.png'
import AddEmployee from './components/add-employee'
import dayjs from 'dayjs'
import Emploees from '@/constant/employees'
import { getUSerInfoAPI, deleteUSerInfoAPI } from '@/api/emploees'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      page: 1,
      size: 5,
      list: [],
      total: 0,
      loading: false,
      showDialog: false,
      defaulrImg: defaulrImg,
      userId: '',
      showRoleDialog: false
    }
  },
  computed: {
    indexTotal() {
      return (this.page - 1) * this.size + 1
    }
  },
  created() {
    this.UserList()
  },
  methods: {
    updataPremiss(id) {
      this.userId = id
      this.showRoleDialog = true
    },
    async UserList() {
      this.loading = true
      const res = await getUSerInfoAPI({
        page: this.page,
        size: this.size
      })
      console.log(res)
      this.list = res.data.rows
      this.total = res.data.total
      this.loading = false
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.size = val
      this.UserList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.UserList()
    },
    /**
     * 处理聘用形式
     */
    formatt(row, column, cellValue) {
      const res = Emploees.hireType
      const obj = res.find(item => item.id === +cellValue)
      return obj ? obj.value : '未知'
    },
    formatDate(val) {
      return val ? dayjs(val).format('YYYY-MM-DD') : '未知'
    },
    /**
     * 删除功能
     */
    delfn(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deleteUSerInfoAPI(id)
        console.log(res)
        this.$message.success('删除成功')
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.UserList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    addfn() {
      this.showDialog = true
    },
    /**
     * 导出
     */
    async  handleDownload() {
      const { data: { rows }} = await getUSerInfoAPI({
        page: 1,
        size: this.total
      })
      console.log(rows)
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const list = this.exculLayout(rows, headersArr, headersRelations)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr,
          data: list,
          filename: '员工信息',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    exculLayout(rows, headersArr, headersRelations) {
      const list = []
      rows.forEach(item => {
        const res = []
        headersArr.forEach(header => {
          const english = headersRelations[header]
          let val = item[english]
          if (english === 'formOfEmployment') {
            const hireType = Emploees.hireType
            const obj = hireType.find(item => item.id === +val)
            val = obj ? obj.value : '未知'
          }
          if (['timeOfEntry', 'correctionTime'].includes(english)) {
            val = this.formatDate(val)
          }
          res.push(val)
        })
        list.push(res)
      })
      return list
    }
  }
}
</script>

<style scoped>
 .avatar{
  width: 80px;
  height: 80px;
  border-radius: 50%;
 }
</style>
